﻿#include "hmi_module.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QDateTime>
#include <QTabWidget>
#include <QMessageBox>
#include <QVBoxLayout>
#include <algorithm>
#include <QColorDialog>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>

// 创建HMIModule实例的函数
HMIModule* createHMIModuleInstance(QWidget* ui, ModbusManager* modbusManager, QObject* parent)
{
    return new HMIModule(ui, modbusManager, parent);
}

HMIModule::HMIModule(QWidget* ui, ModbusManager* modbusManager, QObject *parent)
    : IModule{parent},
    ui_(ui),
    scene_(nullptr),
    modbusManager_(modbusManager),
    button_(nullptr),
    lamp_(nullptr),
    addPage_(nullptr),
    deletePage_(nullptr),
    prePage_(nullptr),
    nextPage_(nullptr)
{
    initSignalSlot();
}

void HMIModule::initSignalSlot()
{
    // 信号连接将在setModbusManager中处理
}

void HMIModule::buttonSignalSlot()
{
    connect(button_, &QPushButton::clicked, this, &HMIModule::prepareToCreateButton);
    connect(lamp_, &QPushButton::clicked, this, &HMIModule::prepareToCreateIndicator);
    connect(addPage_, &QPushButton::clicked, this, &HMIModule::addPage);
    connect(deletePage_, &QPushButton::clicked, this, &HMIModule::deletePage);
    connect(prePage_, &QPushButton::clicked, this, &HMIModule::prePage);
    connect(nextPage_, &QPushButton::clicked, this, &HMIModule::nextPage);
    // 组件创建、复制、粘贴、删除请求
    connect(scene_, &HmiGraphicsScene::componentCreated, this, &HMIModule::onComponentCreated);
    connect(scene_, &HmiGraphicsScene::copyRequestFromScene, this, &HMIModule::onCopyRequested);
    connect(scene_, &HmiGraphicsScene::pasteRequestFromScene, this, &HMIModule::onPasteRequested);
    connect(scene_, &HmiGraphicsScene::deleteRequestFromScene, this, &HMIModule::onDeleteRequested);
}

// 设置工具按钮样式，统一透明背景、图标大小
void HMIModule::setButtonStyle(QPushButton *button, const QString &path)
{
    QString buttonStyle = "QPushButton { background-color: transparent; border: none; }";
    button->setIcon(QIcon(path));
    button->setIconSize(QSize(30, 30));
    button->setStyleSheet(buttonStyle);
    button->setFixedSize(71, 31);
}

// 初始化HMI模块：创建工具栏、图形场景、连接信号槽
void HMIModule::init()
{
    // 动态查找UI元素
    QWidget* hmiToolWidget = ui_->findChild<QWidget*>("hmiToolWidget");
    QWidget* tab_3 = ui_->findChild<QWidget*>("tab_3");
    QGraphicsView* hmiGraphicsView = ui_->findChild<QGraphicsView*>("hmiGraphicsView");
    
    if (!hmiToolWidget || !tab_3 || !hmiGraphicsView) {
        Q_EMIT logMessageGenerated(u8"HMI模块初始化失败：无法找到必要的UI元素");
        return;
    }

    button_ = new QPushButton(hmiToolWidget);
    lamp_ = new QPushButton(hmiToolWidget);
    addPage_ = new QPushButton(hmiToolWidget);
    deletePage_ = new QPushButton(hmiToolWidget);
    prePage_ = new QPushButton(hmiToolWidget);
    nextPage_ = new QPushButton(hmiToolWidget);
    // 设置工具栏的按钮样式
    setButtonStyle(button_, ":/resource/image/button.png");
    setButtonStyle(lamp_, ":/resource/image/lamp.png");
    setButtonStyle(addPage_, ":/resource/image/add.png");
    setButtonStyle(deletePage_, ":/resource/image/delete.png");
    setButtonStyle(prePage_, ":/resource/image/pre.png");
    setButtonStyle(nextPage_, ":/resource/image/next.png");

    // 创建工具栏垂直布局
    QVBoxLayout* toolLayout = new QVBoxLayout(hmiToolWidget);
    toolLayout->setContentsMargins(5, 10, 5, 10);
    toolLayout->setSpacing(10);

    // 添加按钮到工具栏
    toolLayout->addWidget(button_);
    toolLayout->addWidget(lamp_);
    toolLayout->addStretch(1);
    toolLayout->addWidget(addPage_);
    toolLayout->addWidget(deletePage_);
    toolLayout->addWidget(prePage_);
    toolLayout->addWidget(nextPage_);

    // 如果tab_3没有布局，创建一个布局
    if (tab_3->layout() == nullptr)
    {
        QVBoxLayout* layout = new QVBoxLayout(tab_3);
        layout->setContentsMargins(0, 0, 0, 0);
        tab_3->setLayout(layout);
    }

    // 创建场景并设置
    scene_ = new HmiGraphicsScene(hmiGraphicsView, this);
    scene_->setSceneRect(0, 0, 685, 362);
    hmiGraphicsView->setScene(scene_);

    // 连接按钮信号槽
    buttonSignalSlot();
}

// 保存HMI配置到文件
bool HMIModule::saveToFile(const QString& filePath)
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) {
        Q_EMIT logMessageGenerated(u8"保存失败：无法找到tabWidget_2");
        return false;
    }
    QJsonArray pagesArray;
    // 遍历所有页面，序列化页面信息
    for (int i = 0; i < tabWidget->count(); ++i)
    {
        QWidget* page = tabWidget->widget(i);
        QString pageName = tabWidget->tabText(i);
        // 获取页面中的图形视图和场景
        QGraphicsView* graphicsView = page->findChild<QGraphicsView*>();
        if (!graphicsView) continue;
        QGraphicsScene* scene = graphicsView->scene();
        if (!scene) continue;
        // 页面信息JSON对象
        QJsonObject pageObject;
        pageObject["pageName"] = pageName;
        // 存储页面中所有组件的JSON数组
        QJsonArray componentsArray;
        for (QGraphicsItem* item : scene->items())
        {
            HmiComponent* component = dynamic_cast<HmiComponent*>(item);
            if (!component) continue;
            // 组件信息JSON对象
            QJsonObject compObj;
            // 组件类型
            if (dynamic_cast<HmiButton*>(component))
            {
                compObj["type"] = "Button";
            }
            else if (dynamic_cast<HmiIndicator*>(component))
            {
                compObj["type"] = "Indicator";
            }
            // 组件位置
            QPointF pos = component->pos();
            compObj["x"] = pos.x();
            compObj["y"] = pos.y();
            // 颜色保存
            compObj["color"] = component->color().name();
            compObj["onColor"] = component->onColor().name();
            compObj["offColor"] = component->offColor().name();
            // 组件名称
            compObj["componentName"] = component->componentName();
            // 新增地址属性
            compObj["address"] = component->address();
            // 保存尺寸
            compObj["width"] = component->size().width();
            compObj["height"] = component->size().height();
            if (auto btn = dynamic_cast<HmiButton*>(component))
            {
                compObj["isOn"] = btn->isOn();
            }
            componentsArray.append(compObj);
        }
        // 页面关联组件数组
        pageObject["components"] = componentsArray;
        // 页面添加到页面数组
        pagesArray.append(pageObject);
    }
    // 构建根JSON对象并写入文件
    QJsonObject rootObject;
    rootObject["pages"] = pagesArray;
    QJsonDocument doc(rootObject);

    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly))
    {
        Q_EMIT logMessageGenerated(QString(u8"无法打开文件进行保存: ") + filePath);
        return false;
    }
    // 写入格式化的JSON
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();
    Q_EMIT logMessageGenerated(QString(u8"保存成功: ") + filePath);
    // 重置修改状态
    isModified_ = false;
    setModified(false);
    return true;
}

// 从文件加载HMI配置
bool HMIModule::openFromFile(const QString& filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        Q_EMIT logMessageGenerated(QString(u8"无法打开文件进行加载: ") + filePath);
        return false;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError)
    {
        Q_EMIT logMessageGenerated(QString(u8"JSON解析错误: ") + parseError.errorString());
        return false;
    }

    if (!doc.isObject())
    {
        Q_EMIT logMessageGenerated(u8"JSON格式错误，不是对象");
        return false;
    }

    QJsonObject rootObj = doc.object();
    if (!rootObj.contains("pages") || !rootObj["pages"].isArray())
    {
        Q_EMIT logMessageGenerated(u8"JSON缺少pages数组");
        return false;
    }

    QJsonArray pagesArray = rootObj["pages"].toArray();
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) {
        Q_EMIT logMessageGenerated(u8"打开失败：无法找到tabWidget_2");
        return false;
    }

    while (tabWidget->count() > 0)
    {
        QWidget* page = tabWidget->widget(0);
        tabWidget->removeTab(0);
        delete page;
    }

    availablePageNumbers_.clear();

    for (const QJsonValue& pageVal : pagesArray)
    {
        if (!pageVal.isObject()) continue;

        QJsonObject pageObj = pageVal.toObject();
        QString pageName = pageObj["pageName"].toString("Unnamed");

        // 使用新的createNewPage函数创建页面
        QWidget* newPage = createNewPage(pageName, tabWidget);
        tabWidget->addTab(newPage, pageName);

        // 获取新页面的场景
        QGraphicsView* newGraphicsView = newPage->findChild<QGraphicsView*>();
        HmiGraphicsScene* newScene = dynamic_cast<HmiGraphicsScene*>(newGraphicsView->scene());

        // 加载页面中的组件
        QJsonArray compArray = pageObj["components"].toArray();
        for (const QJsonValue& compVal : compArray)
        {
            if (!compVal.isObject()) continue;

            QJsonObject compObj = compVal.toObject();
            QString typeStr = compObj["type"].toString();
            double x = compObj["x"].toDouble();
            double y = compObj["y"].toDouble();
            QString componentName = compObj["componentName"].toString();
            int address = compObj["address"].toInt(0);
            double width = compObj["width"].toDouble(65);
            double height = compObj["height"].toDouble(30);

            // 使用新的createComponentByTypeName函数创建组件
            HmiComponent* newItem = createByTypeName(typeStr);
            if (!newItem) continue;

            // 设置组件属性
            newItem->setSize(width, height);
            newItem->setPos(QPointF(x, y));

            // 直接处理颜色加载，不使用loadColorFromJson函数
            QString colorName = compObj["color"].toString();
            QString onColorName = compObj["onColor"].toString();
            QString offColorName = compObj["offColor"].toString();

            QColor onColor(onColorName);
            if (onColor.isValid())
            {
                newItem->setOnColor(onColor);
            }
            QColor offColor(offColorName);
            if (offColor.isValid())
            {
                newItem->setOffColor(offColor);
            }
            QColor currentColor(colorName);
            if (currentColor.isValid())
            {
                // 恢复当前颜色
                newItem->setColor(currentColor);
            }
            else
            {
                // 如果当前颜色无效，则使用 offColor 作为默认颜色
                newItem->setColor(newItem->offColor());
            }

            // 恢复 isOn 状态
            bool isOn = compObj.contains("isOn") ? compObj["isOn"].toBool() : false;
            if (auto btn = dynamic_cast<HmiButton*>(newItem))
            {
                btn->setOn(isOn);
            }

            newItem->setComponentName(componentName);
            newItem->setAddress(address);
            newScene->addItem(newItem);
            setupNewComponent(newItem);
        }
    }

    if (tabWidget->count() > 0)
    {
        tabWidget->setCurrentIndex(0);
    }

    Q_EMIT logMessageGenerated(QString(u8"打开文件成功: ") + filePath);
    setModified(false);
    return true;
}

// 重置页面：清空所有页，只保留一个空的第一页
void HMIModule::resetPages()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) {
        Q_EMIT logMessageGenerated(u8"重置失败：无法找到tabWidget_2");
        return;
    }

    if (tabWidget->count() == 0) {
        // 没有页面时，重置编号管理并调用addPage创建第一页
        availablePageNumbers_.clear();
        pageCount_ = 0;
        // 调用addPage创建第一页
        addPage();
        return;
    }
    // 有页面时，删除除第一页以外的所有页面
    while (tabWidget->count() > 1)
    {
        QWidget* page = tabWidget->widget(1);
        tabWidget->removeTab(1);
        delete page;
    }
    // 清空第一页场景
    QWidget* firstPage = tabWidget->widget(0);
    QGraphicsView* view = firstPage->findChild<QGraphicsView*>();
    if (view && view->scene())
    {
        view->scene()->clear();
    }
    // 重置页面编号管理
    availablePageNumbers_.clear();
    pageCount_ = 1;
}

// 判断是否有未保存的修改
bool HMIModule::isModified() const
{
    return isModified_;
}

// 设置修改状态
void HMIModule::setModified(bool modified)
{
    isModified_ = modified;
}

// 获取Modbus管理器指针
ModbusManager *HMIModule::getModbusManager() const
{
    return modbusManager_;
}

void HMIModule::againRegisterAllCoils()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;

    // 遍历所有页面
    for (int i = 0; i < tabWidget->count(); ++i)
    {
        QGraphicsView* view = tabWidget->widget(i)->findChild<QGraphicsView*>();
        if (!view) continue;

        // 遍历页面中所有组件
        auto scene = view->scene();
        for (auto *item : scene->items())
        {
            if (auto hmi = dynamic_cast<HmiComponent*>(item))
            {
                // 记录需要监控的地址
                emit signalAddressChanged(-1, hmi->address());
                Q_EMIT logMessageGenerated(QString(u8"HMI组件注册地址：%1").arg(hmi->address()));
            }
        }
    }
}

// 初始化新创建的组件
void HMIModule::setupNewComponent(HmiComponent* item)
{
    if (!item) return;
    // 连接组件的右键菜单信号（复制、删除、修改颜色）
    connect(item, &HmiComponent::copyRequested, this, &HMIModule::onCopyRequested);
    connect(item, &HmiComponent::deleteRequested, this, &HMIModule::onDeleteRequested);
    // connect(item, &HmiComponent::changeOnColorRequested, this, &HMIModule::onChangeOnColorRequested);
    connect(item, &HmiComponent::changeOffColorRequested, this, &HMIModule::onChangeOffColorRequested);
    // 如果是按钮，连接状态变化信号
    if (auto *btn = dynamic_cast<HmiButton*>(item))
    {
        connect(btn, &HmiButton::stateChanged, this, [this, btn](bool on){
            int addr = btn->address();
            // 更新关联的其他组件
            updateByAddress(addr, on);
            // 通过信号请求写线圈操作，避免直接调用ModbusManager
            Q_EMIT IModule::writeCoilRequested(addr, on);
            Q_EMIT logMessageGenerated(QString(u8"HMI按钮状态变化：地址%1，状态%2 -> 已发送写线圈请求").arg(addr).arg(on ? u8"ON" : u8"OFF"));
        });
    }
    emit signalAddressChanged(-1, item->address());
    // 连接地址变化信号
    connect(item, &HmiComponent::coilAddressChanged, this, [this](int oldAddr, int newAddr) {
        Q_EMIT logMessageGenerated(QString(u8"HMI组件地址变更：%1 -> %2").arg(oldAddr).arg(newAddr));
        emit signalAddressChanged(oldAddr, newAddr);
    });
}

// 根据Modbus地址更新所有关联组件的状态
void HMIModule::updateByAddress(int address, bool on)
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;
    // 遍历所有页面
    for (int i = 0; i < tabWidget->count(); ++i)
    {
        QGraphicsView* view = tabWidget->widget(i)->findChild<QGraphicsView*>();
        if (!view) continue;
        // 遍历页面中所有组件
        auto scene = view->scene();
        for (auto *item : scene->items())
        {
            if (auto hmi = dynamic_cast<HmiComponent*>(item))
            {
                // 找到地址匹配的组件
                if (hmi->address() == address)
                {
                    if (auto btn = dynamic_cast<HmiButton*>(hmi))
                    {
                        // 按钮直接更新状态
                        btn->setOn(on);
                    }
                    else
                    {
                        // 指示灯组件更新颜色，ON/OFF对应颜色
                        hmi->setColor(on ? hmi->onColor() : hmi->offColor());
                    }
                }
            }
        }
    }
}

// 获取当前场景
HmiGraphicsScene* HMIModule::getCurrentScene() const
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return nullptr;
    QWidget* currentPage = tabWidget->currentWidget();
    if (!currentPage) return nullptr;

    QGraphicsView* currentGraphicsView = currentPage->findChild<QGraphicsView*>();
    if (!currentGraphicsView) return nullptr;

    return dynamic_cast<HmiGraphicsScene*>(currentGraphicsView->scene());
}

// 根据类型字符串创建组件
HmiComponent* HMIModule::createByTypeName(const QString& type) const
{
    if (type == "Button")
    {
        return new HmiButton();
    }
    else if (type == "Indicator")
    {
        return new HmiIndicator();
    }
    return nullptr;
}

// 创建新页面
QWidget* HMIModule::createNewPage(const QString& pageName, QTabWidget* tabWidget)
{
    QWidget* newPage = new QWidget(tabWidget);
    newPage->setObjectName(pageName);

    // 创建新的图形视图和场景
    QGraphicsView* newGraphicsView = new QGraphicsView(newPage);
    HmiGraphicsScene* newScene = new HmiGraphicsScene(newGraphicsView, this);

    // 设置视图和场景大小
    QSize newViewSize(691, 360);
    newGraphicsView->resize(newViewSize);
    newScene->setSceneRect(0, 0, 691, 360);
    newGraphicsView->setScene(newScene);

    // 设置页面布局
    QVBoxLayout* layout = new QVBoxLayout(newPage);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(newGraphicsView);
    newPage->setLayout(layout);

    // 连接场景信号
    connect(newScene, &HmiGraphicsScene::componentCreated, this, &HMIModule::onComponentCreated);
    connect(newScene, &HmiGraphicsScene::copyRequestFromScene, this, &HMIModule::onCopyRequested);
    connect(newScene, &HmiGraphicsScene::pasteRequestFromScene, this, &HMIModule::onPasteRequested);
    connect(newScene, &HmiGraphicsScene::deleteRequestFromScene, this, &HMIModule::onDeleteRequested);

    return newPage;
}

// 准备创建按钮：设置场景模式为创建按钮
void HMIModule::prepareToCreateButton()
{
    HmiGraphicsScene* currentScene = getCurrentScene();
    if (currentScene)
    {
        // 设置组件类型
        currentScene->setComponentType(ComponentType::BUTTON);
        // 场景模式为创建
        currentScene->setMode(HmiGraphicsScene::Mode::CREATEITEM);
    }
}

// 准备创建指示灯：设置场景模式为创建指示灯
void HMIModule::prepareToCreateIndicator()
{
    HmiGraphicsScene* currentScene = getCurrentScene();
    if (currentScene)
    {
        currentScene->setComponentType(ComponentType::INDICATOR);
        currentScene->setMode(HmiGraphicsScene::Mode::CREATEITEM);
    }
}

// 组件创建完成后调用：初始化组件并标记修改
void HMIModule::onComponentCreated(HmiComponent* item)
{
    // 初始化组件
    setupNewComponent(item);
    // 标记已修改
    setModified(true);
}

// 处理复制组件请求：保存组件属性到复制缓存
void HMIModule::onCopyRequested()
{
    HmiGraphicsScene* currentScene = getCurrentScene();
    if (!currentScene) return;
    // 获取选中的组件
    QList<QGraphicsItem*> selected = currentScene->selectedItems();
    if (selected.isEmpty()) return;
    // 取第一个选中的组件
    HmiComponent* itemToCopy = qgraphicsitem_cast<HmiComponent*>(selected.first());
    if (!itemToCopy) return;
    // 保存组件类型
    if (dynamic_cast<HmiButton*>(itemToCopy))
    {
        copiedType_ = ComponentType::BUTTON;
    }
    else if (dynamic_cast<HmiIndicator*>(itemToCopy))
    {
        copiedType_ = ComponentType::INDICATOR;
    }
    copiedColor_ = itemToCopy->color();
    // 保存组件属性到复制缓存
    copiedOnColor_ = itemToCopy->onColor();
    copiedOffColor_ = itemToCopy->offColor();
    copiedComponentName_ = itemToCopy->componentName();
    copiedAddress_ = itemToCopy->address();
    copiedWidth_ = itemToCopy->size().width();
    copiedHeight_ = itemToCopy->size().height();
    // 标记有复制的组件
    hasCopiedItem_ = true;
}

// 处理粘贴组件请求：从复制缓存创建新组件
void HMIModule::onPasteRequested(const QPointF& scenePos)
{
    // 没有复制的组件则返回
    if (!hasCopiedItem_) return;
    HmiGraphicsScene* currentScene = getCurrentScene();
    if (!currentScene) return;
    // 根据复制的类型创建新组件
    HmiComponent* newItem = nullptr;
    if (copiedType_ == ComponentType::BUTTON)
    {
        newItem = new HmiButton();
    }
    else
    {
        newItem = new HmiIndicator();
    }
    if (newItem)
    {
        // 设置新组件属性，与复制的组件一致
        newItem->setColor(copiedColor_);
        newItem->setOnColor(copiedOnColor_);
        newItem->setOffColor(copiedOffColor_);
        newItem->setComponentName(copiedComponentName_);
        newItem->setAddress(copiedAddress_);
        newItem->setSize(copiedWidth_, copiedHeight_);
        // 粘贴到指定位置
        newItem->setPos(scenePos);
        // 添加到场景并初始化
        currentScene->addItem(newItem);
        setupNewComponent(newItem);
    }
    // 标记为已修改
    setModified(true);
}

// 处理删除组件请求：删除选中的组件
void HMIModule::onDeleteRequested()
{
    HmiGraphicsScene* currentScene = getCurrentScene();
    if (!currentScene) return;
    // 获取选中的组件
    QList<QGraphicsItem*> selected = currentScene->selectedItems();
    if (selected.isEmpty()) return;
    // 删除所有选中的组件
    for (int i = selected.count() - 1; i >= 0; --i)
    {
        HmiComponent* component = dynamic_cast<HmiComponent*>(selected.at(i));
        if (component)
        {
            Q_EMIT logMessageGenerated(QString(u8"HMI组件删除，移除监控地址：%1").arg(component->address()));
        }
        QGraphicsItem* item = selected.at(i);
        currentScene->removeItem(item); // 使用当前页面的 scene
        delete item;
    }
    // 标记为已修改
    setModified(true);
}

// 修改组件OFF状态颜色
void HMIModule::onChangeOffColorRequested(HmiComponent* item)
{
    QColor color = QColorDialog::getColor(item->offColor(), nullptr, u8"选择 OFF 状态颜色");
    if (color.isValid())
    {
        item->setOffColor(color); // 同时更新当前显示颜色
    }
}

// 新增页面的槽函数
void HMIModule::addPage()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;
    int pageNumber;

    if (!availablePageNumbers_.isEmpty())
    {
        std::sort(availablePageNumbers_.begin(), availablePageNumbers_.end());
        pageNumber = availablePageNumbers_.takeFirst();
    }
    else
    {
        pageNumber = ++pageCount_;
    }

    QString pageName = QString("Page %1").arg(pageNumber);
    QWidget* newPage = createNewPage(pageName, tabWidget);

    // 找到插入位置以保持页面编号排序
    int insertIndex = tabWidget->count();
    for (int i = 0; i < tabWidget->count(); ++i)
    {
        QString existName = tabWidget->tabText(i);
        int existNum = existName.mid(5).toInt();
        if (pageNumber < existNum)
        {
            insertIndex = i;
            break;
        }
    }

    tabWidget->insertTab(insertIndex, newPage, pageName);
    tabWidget->setCurrentWidget(newPage);

    Q_EMIT logMessageGenerated(QString(u8"添加页面: ") + pageName);
    setModified(true);
}

// 删除当前页面
void HMIModule::deletePage()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;
    int currentIndex = tabWidget->currentIndex();
    // 至少保留一个页面
    if (tabWidget->count() == 1) return;

    if (currentIndex >= 0)
    {
        // 获取要删除的页面
        QWidget* currentPage = tabWidget->widget(currentIndex);
        QString pageName = tabWidget->tabText(currentIndex);
        // 从页面名称中提取页面编号
        int pageNumber = pageName.remove("Page ").toInt();
        // 将删除的页面编号添加到可用列表中
        availablePageNumbers_.append(pageNumber);
        std::sort(availablePageNumbers_.begin(), availablePageNumbers_.end());
        // 从 TabWidget 中移除页面
        tabWidget->removeTab(currentIndex);
        // 删除页面
        delete currentPage;
        // 记录日志
        Q_EMIT logMessageGenerated(QString(u8"删除页面: ") + pageName);
    }
    setModified(true); // 标记已修改
}

// 切换到上一页
void HMIModule::prePage()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;
    int currentIndex = tabWidget->currentIndex();
    // 不是第一页则切换
    if (currentIndex > 0)
    {
        tabWidget->setCurrentIndex(currentIndex - 1);
    }
}

// 切换到下一页
void HMIModule::nextPage()
{
    QTabWidget* tabWidget = ui_->findChild<QTabWidget*>("tabWidget_2");
    if (!tabWidget) return;
    int currentIndex = tabWidget->currentIndex();
    // 不是最后一页则切换
    if (currentIndex < tabWidget->count() - 1)
    {
        tabWidget->setCurrentIndex(currentIndex + 1);
    }
}

// IModule接口实现
void HMIModule::reset()
{
    resetPages();
}

QString HMIModule::getFileFilter() const
{
    return QString(u8"HMI文件 (*.hmi)");
}

QString HMIModule::getModuleName() const
{
    return QString(u8"HMI");
}

// 仿真相关方法实现
void HMIModule::startSimulation(const QString& serialPort, int baudRate, int dataBits, int stopBits, int parity)
{
    if (!modbusManager_) return;
    
    // 重新注册所有线圈
    againRegisterAllCoils();
    Q_EMIT logMessageGenerated(QString(u8"HMI仿真已启动：串口：%1，波特率：%2")
                             .arg(serialPort, QString::number(baudRate)));
}

void HMIModule::stopSimulation()
{
    if (!modbusManager_) return;
    
    Q_EMIT logMessageGenerated(u8"HMI仿真已停止");
}

bool HMIModule::isSimulationRunning() const
{
    return modbusManager_ != nullptr;
}

// 设置Modbus管理器
void HMIModule::setModbusManager(ModbusManager* modbusManager)
{
    modbusManager_ = modbusManager;
    
    // 信号连接将通过主项目处理，避免直接连接ModbusManager
    Q_EMIT logMessageGenerated(u8"HMI模块已设置ModbusManager");
}

// 实现IModule接口的Modbus数据更新方法
void HMIModule::onCoilUpdated(int address, bool value)
{
    // 调用现有的updateByAddress方法来更新HMI组件
    updateByAddress(address, value);
    Q_EMIT logMessageGenerated(QString(u8"HMI收到线圈更新：地址%1，值%2").arg(address).arg(value ? u8"ON" : u8"OFF"));
}

void HMIModule::onRegisterUpdated(int address, quint16 value)
{
    // 这里可以处理寄存器更新，比如更新显示数值的组件
    Q_EMIT logMessageGenerated(QString(u8"HMI收到寄存器更新：地址%1，值%2").arg(address).arg(value));
}
